﻿package  com.sos.ui {
	
	import com.deadreckoned.assetmanager.AssetManager;
	import com.sos.core.cards.CardBallCondition;
	import com.sos.core.cards.CardManager;
	import com.sos.core.game.GameActionCard;
	import com.sos.core.game.GameRole;
	import com.sos.core.game.GameStatus;
	import com.sos.core.Position;
	import com.sos.core.Role;
	import com.sos.core.UniqueClassType;
	import com.sos.logging.Logger;
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.events.MouseEvent;
	import flash.filters.*;
	
	
	public class ActionCardClip extends MovieClip {
		
		public var gameActionCard:GameActionCard;
		
	 	public var order:uint;
		public var instanceId:String;
		public var img:MovieClip;
		public var stayUp:Boolean;
		public var special:Boolean;
		public var cardOrder:uint;
		public var logDepthIndex:uint;
		public var graveOrder:uint = 0;
		
		public var playable:uint;
		public var isPlayed:Boolean;
		public var playOrder:Number;
		
		public var discardOrder:Number;
		public var isQueuedForDiscard:Boolean;
		
		public var targetParamName:String;
		public var hasTarget:Boolean;
		public var isTargeting:Boolean;
		public var targetType:String;
		public var validTargets:Array;
		public var targetId:String;
		public var hasNewCardGlow:Boolean = false;
		
		public var cardZone:String;
		
		var loader = new Loader();
		var loaderLarge = new Loader();
		var baseHeight = 154;
		var baseWidth = 97;
		
		var greyOutFilter = new ColorMatrixFilter([0.3086, 0.6094, 0.0820, 0, 0, 0.3086, 0.6094, 0.0820, 0, 0, 0.3086, 0.6094, 0.0820, 0, 0, 0, 0, 0, 1, 0]);
		var activeFilter = new GlowFilter(0x33CC00, .75, 20, 20, 2, 2, false, false);
		var newCardFilter = new GlowFilter(0xFFFFFF, .75, 20, 20, 2, 2, false, false);
		var discardFilter = new GlowFilter(0xCC6600, .75, 20, 20, 2, 2, false, false);
		var oppFilter = new GlowFilter(0xFF0000, .75, 15, 15, 2, 2, false, false);
		var lowStamFilter = new GlowFilter(0xFF0000, .75, 20, 20, 2, 2, true, false);
		var dropFilter:BitmapFilter;
		
		var lgTxtArray:Array = new Array();
		var smallTxtArray:Array = new Array();
		
		private var playArea:PlayArea;
			
		public function ActionCardClip(acData:GameActionCard, playArea:PlayArea, order:uint, cardZone:String = "hand") {
			
			gameActionCard = acData;
			this.cardOrder = order;
			this.name = acData.name;
			this.instanceId = acData.instanceId.toString();
			//Logger.debug("UI > ACTIONCARD > Instancing " + name + " with instanceId " + instanceId);
			this.playArea = playArea;
			this.playable = 1;
			this.cardZone = cardZone;
			largeBlank.visible = false;
			stayUp = false;
			isTargeting = false;
			forbiddenSign.visible = false;
			lg_cardName.text = acData.skill.toString() + "- " + acData.name;
			lg_cardCost.text = acData.cost.toString();
			lg_cardText.htmlText = acData.actionText;
			
			if (acData.uniqueClass != null) {
				//Logger.debug("UI > ACTIONCARD > Unique card found " + name + " with class: " + acData.uniqueClass);
				if (acData.uniqueClassType == UniqueClassType.SELF)
					lg_unique.text = 'Unique';
				else if (acData.uniqueClassType == UniqueClassType.SHARED)
					lg_unique.text = acData.uniqueClass;
			}
			
			
			
			if (gameActionCard.subtype)
				lg_type.text = gameActionCard.subtype.name;
			else {
				lg_type.text = CardManager.getCardManager().getActionCardById(gameActionCard.cardId).subtype.name;
			}
			
			if (gameActionCard.special === true)
				lg_type.text = 'Special';
			
			//REPLACE PLACEHOLDER STRING WITH ICON
			//this.replacePlaceholders();
			
			lgTxtArray[0] = lg_cardName;
			lgTxtArray[1] = lg_cardCost;
			lgTxtArray[2] = lg_cardText;
			
			
			
			if (gameActionCard.hasTargetInput)
			{
				trace("Targeted Card found: " + this.name);
				hasTarget = true;
				loadTargets();
				
			}
			else {
				//trace("Card " + this.name + " has no target input");
			}
			
			//trace('PLAYER INIT: ' + plData.name + ' SIDE: ' + side + ' POSITION : ' + position);
			
			var assetManager:AssetManager = AssetManager.getInstance();
			
			var imgKey:String;
			if (acData.image) 
				imgKey = acData.image;
			else
				imgKey = 'ACBlank';
			loaderLarge = new Bitmap(assetManager.get(imgKey).asset, "auto", true);
			
			loaderLarge.name = 'largeImage';
			
			loaderLarge.x=-loaderLarge.width/2;
			loaderLarge.y=-loaderLarge.height/2;
			
			//loaderLarge.y=-20;
			dropFilter = this.getDropShadowFilter();
			loaderLarge.filters = [dropFilter];
			addChildAt(loaderLarge, 1);
			//loaderLarge.visible = false;
			
			
			
			if (cardZone != "roundView") {
				this.addEventListener(MouseEvent.ROLL_OVER,zoomIn,false,0,true);
				this.addEventListener(MouseEvent.ROLL_OUT, zoomOut, false, 0, true);
				this.scaleX = 0.7;
				this.scaleY = 0.7;
			}
			if (cardZone == "hand") {
				
				this.addEventListener(MouseEvent.CLICK, handleLeftClick, false, 0, true);
				setPlayability();
			}
		}
		
		
		
		public function loadTargets():void {
			
			for (var tKey in gameActionCard.validTargets) {
				//trace("Target " + tKey + " type: " + gameActionCard.validTargets[tKey].type);
				targetType = gameActionCard.validTargets[tKey].type;
				targetParamName = gameActionCard.validTargets[tKey].name;
				if (targetType == 'target')
					targetType = 'player';
				validTargets = new Array();
				for each (var vTarget:String in gameActionCard.validTargets[tKey].validTargets) {
					validTargets.push(vTarget);
					//Logger.debug("UI > ACTIONCARD > " + name + " queued targetId " + vTarget);
				}
			
			}
			
		}
		
		public function moveToSide(targetSide:String, cardLogOrder:uint):void {
			if (targetSide == 'home') {
				this.x = playArea.ac1.x + ((cardLogOrder - 1) * 70);
				this.y = playArea.ac1.y;
				
			}
			else {
				this.x = playArea.acAway.x - ((cardLogOrder - 1) * 70);
				this.y = playArea.acAway.y;
				//cardLogOrder += 20;
			}
			//playArea.setChildIndex(this, cardLogOrder);
			Logger.debug("UI > ACTIONCARD > " + name + " set to index " + cardLogOrder.toString());
			this.cardOrder = cardLogOrder;
			this.logDepthIndex = playArea.getChildIndex(this);
			this.addEventListener(MouseEvent.ROLL_OVER,zoomIn,false,0,true);
			this.addEventListener(MouseEvent.ROLL_OUT, zoomOut, false, 0, true);
			
			
			this.scaleX = 0.7;
			this.scaleY = 0.7;
		}
		
		public function addToHand(showGlow:Boolean = false):void {
			this.addEventListener(MouseEvent.CLICK, handleLeftClick, false, 0, true);
			
			if (showGlow) {
				hasNewCardGlow = true;
				loaderLarge.filters.push(newCardFilter);
			}
		}
		
		public function unsetNewCardGlow():void {
			if (hasNewCardGlow) {
				hasNewCardGlow = false;
				filters = [dropFilter];
			}
		}
		
		public function sendToGrave():void {
			if (this.cardZone == 'hand') {
				this.removeEventListener(MouseEvent.CLICK, handleLeftClick);
				filters = [dropFilter];
				playArea.removeCardFromHand(this);
				cardZone = "grave";
				playArea.addCardToGrave(playArea.clientSide, this);
			}
			else {
				this.removeEventListener(MouseEvent.CLICK, setCardAsTarget);
				playArea.homeGraveOverlay.addCard(this);
			}
			
			
		}
		
		public function addToCardSelectionOverlay():void {
			//trace("Adding", this.name, "to card selection overlay from", this.parent.name);
			this.addEventListener(MouseEvent.CLICK, setCardAsTarget, false, 0, true);
			if (this.cardZone == 'grave') {
				//GraveOverlayClip(this.parent).removeCard(this.instanceId);
			}
			playArea.overlay.addCard(this);
			
			
		}
		
		function enterTargetMode():void {
			if (cardZone == "hand") {
				this.removeEventListener(MouseEvent.CLICK, handleLeftClick);
				if (this.playable == 0)
				{
					filters = [dropFilter];
				}
			}
			this.addEventListener(MouseEvent.CLICK, setCardAsTarget, false, 0, true);
			
		}
		
		function exitTargetMode():void {
			
			this.removeEventListener(MouseEvent.CLICK, setCardAsTarget);
			
			if (cardZone == "hand") {
				this.addEventListener(MouseEvent.CLICK, handleLeftClick, false, 0, true);
				if (this.playable == 0)
				{
					filters = [greyOutFilter];
				}
			}
		}
		
		
		/***********************************
		*	SETS THIS CARD AS TARGET 
		*
		***********************************/
		
		function setCardAsTarget(e:MouseEvent):void {
			
			playArea.handCardList[playArea.targetingCardId].setTarget(instanceId);
			
		}
		
		
		/*****************************************
		*	SAVES INFO ABOUT THE CARD'S TARGET
		*	id = instanceId/effectId
		*****************************************/
		public function setTarget(id:String):void {
			targetId = id;
			playArea.exitTargetMode(this.targetType);
			playArea.queueCard(this);
			isPlayed = true;
			playOrder = playArea.playCounter;
			playOrderBox.text = playOrder.toString();
			loaderLarge.filters = [activeFilter];
			if (this.targetType == 'player')
				trace("CARD #" + playArea.playCounter.toString() + " IS: " + lg_cardName.text + " WITH TARGET " + playArea.fieldMc.playerList[id].playerName + " (" + id + ")");
			else if (this.targetType == 'effect')
				trace("CARD #" + playArea.playCounter.toString() + " IS: " + lg_cardName.text + " WITH TARGET " + playArea.effectList[id].effectName + " (" + id + ")");
			else if (this.targetType == 'card')
				trace("CARD #" + playArea.playCounter.toString() + " IS: " + lg_cardName.text + " WITH TARGET " + playArea.cardList[id].name + " (" + id + ")");
			var e:MouseEvent = new MouseEvent("CLICK");
			stayUp = false;
			isTargeting = false;
			zoomOut(e);
			
		}
		
		public function setPlayability():void {
			
			var playability:Boolean = true;
			var pl:PlayerClip = playArea.fieldMc.playerList[playArea.activePlayers[playArea.clientSide]];
			
			//if (!pl.gamePlayer.canPlayCards) playability = false;
			if ((gameActionCard.cost > 0) && (gameActionCard.cost > pl.gamePlayer.gameStats.stamina)) {
				playability = false;
				Logger.debug('UI > ActionCardClip > Cost for ' + name + " is " + gameActionCard.cost.toString() + " and playerStamina is " + pl.gamePlayer.gameStats.stamina.toString());
			}
			if ((gameActionCard.role != Role.NONE) && (gameActionCard.role != pl.gamePlayer.role)) {
				playability = false;
				//Logger.debug('UI > ActionCardClip > Role mismatch for ' + name);
			}
			if (gameActionCard.ballCondition != CardBallCondition.ALWAYS) {
				if ((gameActionCard.ballCondition == CardBallCondition.WITH_BALL) && (playArea.clientRole != GameRole.ATTACK)) playability = false;
				if ((gameActionCard.ballCondition == CardBallCondition.WITHOUT_BALL) && (playArea.clientRole != GameRole.DEFENCE)) playability = false;
			}
			var cardSchools:Array = gameActionCard.schools;
			var playerSchools:Array = pl.gamePlayer.schools;
			
			var schoolMatch:Boolean = false;
			var i:uint = 0;
			while ((schoolMatch == false) && (i < cardSchools.length)) {
				//Logger.debug('UI > ActionCardClip > Checking school ' + cardSchools[i].name + ' for ' + name);
				if (playerSchools.indexOf(cardSchools[i]) != -1) {
					schoolMatch = true;
					//Logger.debug('UI > ActionCardClip > School ' + cardSchools[i].name + ' found in ' + pl.playerName);
				}
				else {
					//Logger.debug('UI > ActionCardClip > School ' + cardSchools[i].name + ' not found in ' + pl.playerName);
				}
				i++;
			}
			
			if ((gameActionCard.targetPositions.indexOf(Position.ANY) < 0) && (gameActionCard.targetPositions.indexOf(Position.getBySign(pl.position)) < 0)) playability = false;
			
			
			if (!schoolMatch) {
				playability = false;
				//Logger.debug('UI > ActionCardClip > No school match found for ' + name + " in  " + pl.playerName);
				for (i = 0; i < playerSchools.length; i++) {
					//Logger.debug('UI > ActionCardClip > School #' + i + " for  " + pl.playerName + " is " + playerSchools[i]);
				}
			}
			
			if ((gameActionCard.hasTargetInput) && (gameActionCard.validTargets.length == 0)) {
				playability = false;
				//Logger.debug('UI > ActionCardClip > No target available for ' + name);
			}
			
			//DISABLING CONTROLS
			playability = true;
			
			if (playability) {
				playable = 1;
				forbiddenSign.visible = false;
				
				
			}
			else {
				playable = 0;
				forbiddenSign.visible = true;
				
			}
		}
		
		public function hidePlayabilitySign():void {
			forbiddenSign.visible = false;
		}
		
		function handleLeftClick(e:MouseEvent) {
			if (playArea.currentStatus == GameStatus.PLAY) 
				playCard(e);
			else if (playArea.currentStatus == GameStatus.DISCARD) {
				discardCard(e);
			}
		}
		
		function discardCard(e:MouseEvent) {
			if (isQueuedForDiscard == true) {
				filters = [dropFilter];
				playArea.unQueueCardForDiscard(this);
				isQueuedForDiscard = false;
				discardOrder = 0;
				playOrderBox.text = "";
			}
			else {
				filters = [discardFilter];
				discardOrder = playArea.queueCardForDiscard(this);
				playOrderBox.text = discardOrder.toString();
				isQueuedForDiscard = true;
				trace("DISCARDED CARD #" + playArea.discardCounter.toString() + " IS: " + lg_cardName.text);
				zoomOut(e);
			}
		}
		
		function playCard(e:MouseEvent):void {
			
			if (isPlayed == true) { //REMOVE CARD FROM PLAY LIST AND UNSET TARGETS
				
				playArea.unQueueCard(this);
				isPlayed = false;
				playOrder = 0;
				playOrderBox.text = "";
				
				if (hasTarget == true) {
					switch (targetType) {
						case "player":
							playArea.stopHighlightingPlayer(playArea.fieldMc.playerList[targetId]);
						break;
						case "effect":
							var effectTarget:String;
							for each (effectTarget in playArea.effectList[targetId].targetList) {
										playArea.fieldMc.playerList[effectTarget].effectBox.largeIconList[targetId].targeted.visible = false;
										playArea.fieldMc.playerList[effectTarget].effectBox.smallIconList[targetId].targeted.visible = false;
							}
						break;
						
					}
										
					targetId = null;
				}
				
				trace("CARD " + lg_cardName.text + " REMOVED FROM PLAY LIST");
				loaderLarge.filters = [dropFilter];
				zoomOut(e);
				
			}
			else if (isTargeting == true) { // EXIT TARGET MODE WITHOUT PLAYING THE CARD 
				
				playArea.exitTargetMode(this.targetType);
				isTargeting = false;
				stayUp = false;
				playArea.targetingCardId = '';
			}
			else if ((playable == true)&&(playArea.targetLockStatus(instanceId) == false)) { // PLAY THE CARD
				if (playArea.playCounter >= playArea.maxPlayables) //CARD LIMIT REACHED
				{
					trace("CARD LIMIT REACHED (" + playArea.maxPlayables + ")");
				}
				else
				{
					if (hasTarget == false) //PLAY THE CARD (IT HAS NO USER-DEFINED TARGETS)
					{
						playArea.queueCard(this);
						isPlayed = true;
						playOrder = playArea.playCounter;
						playOrderBox.text = playOrder.toString();
						loaderLarge.filters = [activeFilter];
						//trace("CARD #" + playArea.playCounter.toString() + " IS: " + lg_cardName.text);
						zoomOut(e);
					}
					else // START TARGETING
					{
						trace("ENTERING TARGET SELECTION MODE ", validTargets, this.targetType);
						isTargeting = true;
						stayUp = true;
						playArea.targetingCardId = instanceId;
						//var tmpArr:Array = ["4","5"];
						playArea.playMenu.setTargetingMessage("Select target for " + lg_cardName.text);
						playArea.enterTargetMode(validTargets, this.instanceId, this, this.targetType);
					}
					
				}
			}
			else {
				trace("CARD " + lg_cardName.text + " ISN'T PLAYABLE");
			}
		
		}
		
		
		
		function updateOrder(newOrder:Number) {
			playOrder = newOrder;
			playOrderBox.text = playOrder.toString();
		}
		
		function addFilter(filter:BitmapFilter) {
			var tmpArr = filters;
			tmpArr.push(filter);
			loaderLarge.filters = tmpArr;
		}
		
		
		
		function zoomIn(e:MouseEvent):void{
			//trace("ENTERING " + e.target.name + " FROM " + playerName);
			if ((e.target.name != 'largeImage')&&(playArea.targetLockStatus(instanceId) == false))
			{
				this.scaleX = 1;
				this.scaleY = 1;
				if (hasNewCardGlow) {
					unsetNewCardGlow();
				}
				
				if (cardZone == 'hand')
					playArea.setChildIndex(this, 9);
				else if (cardZone == 'grave' || cardZone == 'roundView')
					this.parent.addChild(this);
				
				if (hasTarget && isPlayed) {
					
					if (targetType == 'player')
						playArea.highlightPlayer(playArea.fieldMc.playerList[targetId]);
					else if (targetType == 'effect') {
						
						var effectTarget:String;
						for each (effectTarget in playArea.effectList[targetId].targetList) {
								playArea.fieldMc.playerList[effectTarget].effectBox.largeIconList[targetId].targeted.visible = true;
								playArea.fieldMc.playerList[effectTarget].effectBox.smallIconList[targetId].targeted.visible = true;
						}
					}
				}
				
			}
		}
		
		function zoomOut(e:MouseEvent):void{
			//trace("EXITING " + e.target.name + " FROM " + playerName);
			if (stayUp == false)
			{
				this.scaleX = 0.7;
				this.scaleY = 0.7;
				
				//trace("SETTING INDEX BACK TO " + this.cardOrder.toString());
				if (cardZone == 'hand') 
					playArea.setChildIndex(this, this.cardOrder);
				else if (cardZone == 'grave') 
					this.parent.setChildIndex(this, this.graveOrder);
				else if (cardZone == 'roundView') 
					playArea.setChildIndex(this, this.logDepthIndex);
				//addChildAt(loader, 1);
				if (hasTarget && isPlayed) {
					
					if (targetType == 'player')
						playArea.stopHighlightingPlayer(playArea.fieldMc.playerList[targetId]);
					else if (targetType == 'effect') {
						
						var effectTarget:String;
						for each (effectTarget in playArea.effectList[targetId].targetList) {
									playArea.fieldMc.playerList[effectTarget].effectBox.largeIconList[targetId].targeted.visible = false;
									playArea.fieldMc.playerList[effectTarget].effectBox.smallIconList[targetId].targeted.visible = false;
						}
					}
				}
			}
		}
		
		public function dispose():void {
			Logger.debug("UI > ActionCardClip > Disposing of " + this.name);
			this.playArea = null;
		}
				
		private function getDropShadowFilter(color:Number = 0x000000):BitmapFilter {
			
			var angle:Number = 45;
			var alpha:Number = 0.8;
			var blurX:Number = 8;
			var blurY:Number = 8;
			var distance:Number = 15;
			var strength:Number = 0.65;
			var inner:Boolean = false;
			var knockout:Boolean = false;
			var quality:Number = BitmapFilterQuality.HIGH;
			return new DropShadowFilter(distance,
										angle,
										color,
										alpha,
										blurX,
										blurY,
										strength,
										quality,
										inner,
										knockout);
		}
		
		
		
	} 
}